package com.camel.base.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.base.model.TbColumn;
import com.camel.base.service.TbColumnService;
import com.camel.core.controller.BaseCommonController;
import com.camel.core.entity.Result;
import com.camel.core.exceptions.CustomException;
import com.camel.core.service.BaseCommonService;
import com.camel.core.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * @author camel
 */
@RestController
@RequestMapping("tbColumn")
public class TbColumnController extends BaseCommonController<TbColumn> {

    @Autowired
    private TbColumnService<TbColumn> service;

    @PostMapping("/save")
    private Result save(@RequestBody List<TbColumn> params) {
        for (TbColumn param : params) {
            param.setCreator(StpUtil.getLoginIdAsInt());
            param.setUpdator(StpUtil.getLoginIdAsInt());
            param.setCreateAt(new Date());
            param.setUpdateAt(new Date());

            Integer sourceId = param.getSourceId();
            String schemaName = param.getSchemaName();
            String tableName = param.getTableName();
            String columnName = param.getColumnName();
            TbColumn one = service.getOne(new QueryWrapper<TbColumn>()
                    .eq("source_id", sourceId)
                    .eq("schema_name", schemaName)
                    .eq("table_name", tableName)
                    .eq("column_name", columnName));
            if (ObjectUtils.isEmpty(one)) {
                service.save(param);
            } else {
                param.setId(one.getId());
                service.updateById(param);
            }

        }
        return ResultUtil.success("操作成功");
    }

    @Override
    public boolean deleteAble(Serializable id) {
        TbColumn byId = service.getById(id);
        if (ObjectUtils.isEmpty(byId)) {
            throw new CustomException("删除失败: " + getMouduleName() + "不存在");
        }
        return true;
    }

    @Override
    public BaseCommonService<TbColumn> getiService() {
        return service;
    }

    @Override
    public String getMouduleName() {
        return "数据列";
    }
}
